"""
桌面客户端应用
基于tkinter的简单GUI客户端
"""
import tkinter as tk
from tkinter import ttk, scrolledtext
import requests
from typing import List, Dict
import threading


class MedicalLiteratureClient:
    """医学文献检索客户端"""
    
    def __init__(self, root):
        self.root = root
        self.root.title("医学文献智能检索与摘要平台")
        self.root.geometry("1000x700")
        
        self.api_url = "http://localhost:8000"
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置用户界面"""
        # 标题
        title_frame = tk.Frame(self.root, bg="#667eea", pady=20)
        title_frame.pack(fill=tk.X)
        
        title_label = tk.Label(
            title_frame,
            text="🏥 医学文献智能检索与摘要平台",
            font=("Arial", 20, "bold"),
            bg="#667eea",
            fg="white"
        )
        title_label.pack()
        
        subtitle_label = tk.Label(
            title_frame,
            text="基于大模型的医学文献检索和自动摘要系统",
            font=("Arial", 12),
            bg="#667eea",
            fg="white"
        )
        subtitle_label.pack()
        
        # 搜索区域
        search_frame = tk.Frame(self.root, padx=20, pady=20)
        search_frame.pack(fill=tk.X)
        
        tk.Label(
            search_frame,
            text="搜索查询:",
            font=("Arial", 12, "bold")
        ).pack(anchor=tk.W)
        
        self.query_entry = tk.Entry(
            search_frame,
            font=("Arial", 12),
            width=80
        )
        self.query_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, pady=5)
        
        self.search_button = tk.Button(
            search_frame,
            text="🔍 搜索",
            command=self.search,
            font=("Arial", 12, "bold"),
            bg="#667eea",
            fg="white",
            padx=20
        )
        self.search_button.pack(side=tk.LEFT, padx=10)
        
        # 摘要区域
        summary_frame = tk.Frame(self.root, padx=20, pady=10)
        summary_frame.pack(fill=tk.BOTH, expand=True)
        
        tk.Label(
            summary_frame,
            text="📋 智能摘要",
            font=("Arial", 12, "bold")
        ).pack(anchor=tk.W)
        
        self.summary_text = scrolledtext.ScrolledText(
            summary_frame,
            height=6,
            font=("Arial", 11),
            wrap=tk.WORD
        )
        self.summary_text.pack(fill=tk.BOTH, expand=True)
        
        # 结果区域
        results_frame = tk.Frame(self.root, padx=20, pady=10)
        results_frame.pack(fill=tk.BOTH, expand=True)
        
        results_header = tk.Frame(results_frame)
        results_header.pack(fill=tk.X)
        
        tk.Label(
            results_header,
            text="📚 检索结果",
            font=("Arial", 12, "bold")
        ).pack(side=tk.LEFT)
        
        self.results_count_label = tk.Label(
            results_header,
            text="",
            font=("Arial", 11),
            fg="#666"
        )
        self.results_count_label.pack(side=tk.LEFT, padx=10)
        
        # 创建Notebook用于显示结果
        self.results_notebook = ttk.Notebook(results_frame)
        self.results_notebook.pack(fill=tk.BOTH, expand=True)
        
        # 状态栏
        self.status_bar = tk.Label(
            self.root,
            text="就绪",
            bd=1,
            relief=tk.SUNKEN,
            anchor=tk.W
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 绑定回车键
        self.query_entry.bind('<Return>', lambda e: self.search())
    
    def search(self):
        """执行搜索"""
        query = self.query_entry.get().strip()
        
        if not query:
            self.status_bar.config(text="错误: 请输入搜索查询")
            return
        
        # 禁用搜索按钮
        self.search_button.config(state=tk.DISABLED)
        self.status_bar.config(text="正在搜索...")
        
        # 在新线程中执行搜索
        threading.Thread(target=self._perform_search, args=(query,), daemon=True).start()
    
    def _perform_search(self, query):
        """执行搜索请求"""
        try:
            response = requests.post(
                f"{self.api_url}/search",
                json={"query": query, "top_k": 10},
                timeout=60
            )
            response.raise_for_status()
            results = response.json()
            
            # 更新UI
            self.root.after(0, self._update_results, results)
            
        except Exception as e:
            self.root.after(0, self._show_error, str(e))
    
    def _update_results(self, results):
        """更新结果显示"""
        # 清空之前的标签页
        for tab_id in self.results_notebook.tabs():
            self.results_notebook.forget(tab_id)
        
        # 更新摘要
        self.summary_text.delete(1.0, tk.END)
        if results.get("summary"):
            self.summary_text.insert(1.0, results["summary"])
        
        # 显示结果
        papers = results.get("papers", [])
        self.results_count_label.config(text=f"找到 {len(papers)} 篇论文")
        
        if papers:
            for i, paper in enumerate(papers, 1):
                # 创建结果标签页
                result_frame = tk.Frame(self.results_notebook)
                self.results_notebook.add(result_frame, text=f"论文 {i}")
                
                # 显示论文信息
                self._display_paper(result_frame, paper, i)
        
        self.search_button.config(state=tk.NORMAL)
        self.status_bar.config(text="搜索完成")
    
    def _display_paper(self, parent_frame, paper, index):
        """在框架中显示论文信息"""
        # 标题
        title_label = tk.Label(
            parent_frame,
            text=paper.get("title", "无标题"),
            font=("Arial", 14, "bold"),
            wraplength=900,
            justify=tk.LEFT
        )
        title_label.pack(anchor=tk.W, padx=20, pady=10)
        
        # 元信息
        meta_frame = tk.Frame(parent_frame)
        meta_frame.pack(anchor=tk.W, padx=20, pady=5)
        
        authors = ", ".join(paper.get("authors", [])[:5])
        meta_text = f"作者: {authors or '未知'}  |  期刊: {paper.get('journal', '未知')}  |  日期: {paper.get('publication_date', '未知')}"
        meta_label = tk.Label(
            meta_frame,
            text=meta_text,
            font=("Arial", 10),
            fg="#666",
            wraplength=900,
            justify=tk.LEFT
        )
        meta_label.pack(anchor=tk.W)
        
        # 相关性分数
        if paper.get("relevance_score"):
            score_label = tk.Label(
                parent_frame,
                text=f"相关性: {paper['relevance_score'] * 100:.1f}%",
                font=("Arial", 11, "bold"),
                fg="#667eea"
            )
            score_label.pack(anchor=tk.W, padx=20)
        
        # 摘要
        abstract_label = tk.Label(
            parent_frame,
            text="摘要:",
            font=("Arial", 11, "bold")
        )
        abstract_label.pack(anchor=tk.W, padx=20, pady=(10, 5))
        
        abstract_text = scrolledtext.ScrolledText(
            parent_frame,
            height=8,
            font=("Arial", 10),
            wrap=tk.WORD
        )
        abstract_text.pack(fill=tk.BOTH, expand=True, padx=20, pady=5)
        abstract_text.insert(1.0, paper.get("abstract", "无摘要"))
        abstract_text.config(state=tk.DISABLED)
        
        # 链接按钮
        if paper.get("full_text_url"):
            link_button = tk.Button(
                parent_frame,
                text="🔗 查看完整论文",
                command=lambda: self._open_url(paper["full_text_url"]),
                bg="#667eea",
                fg="white",
                padx=20,
                pady=5
            )
            link_button.pack(side=tk.RIGHT, padx=20, pady=10)
    
    def _open_url(self, url):
        """打开URL"""
        import webbrowser
        webbrowser.open(url)
    
    def _show_error(self, error_msg):
        """显示错误信息"""
        self.search_button.config(state=tk.NORMAL)
        self.status_bar.config(text=f"错误: {error_msg}")


def main():
    """启动客户端"""
    root = tk.Tk()
    app = MedicalLiteratureClient(root)
    root.mainloop()


if __name__ == "__main__":
    main()
